package de.jtserver;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
import java.util.logging.Logger;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.mozilla.javascript.Context;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;

import de.jtserver.model.JTalkScript;

public class JScriptHelper {

	public static Logger logger = Logger.getLogger("de.jtserver.JTalk");
	
	public static ScriptableObject initJScript(Context ctx, String script) throws FileNotFoundException, IOException {
		ScriptableObject scope = ctx.initStandardObjects();
		ctx.evaluateString(scope, "var CanvasRenderingContext2D = false;", "<cmd>", 1, null);
		ctx.evaluateString(scope, "var isServer = true;", "<cmd>", 1, null);
		ctx.evaluateString(scope, "var javaobjects = new java.util.HashMap();", "<cmd>", 1, null);
		ctx.evaluateString(scope, script, "<cmd>", 1, null);
		String scriptFromFile = readFile("js/init.js");
		ctx.evaluateString(scope, scriptFromFile, "<cmd>", 1, null);

		ScriptableObject.putProperty(scope, "logger", logger);
		return scope;
	}

	public static String getScript(String owner) throws FileNotFoundException, IOException {
		return getJTalkScript(owner).getScript();
	}

	public static JTalkScript getJTalkScript(String owner) throws FileNotFoundException, IOException {
		JTalkDAO dao = new JTalkDAO();
		List l = dao.findByOwner(owner);
		JTalkScript jts = null;
		if (l == null || l.size() == 0) {
			String script = readFile("js/jtalk.js");
			jts = dao.save(owner, script);
		} else {
			jts = (JTalkScript) l.get(0);
		}
		return jts;
	}
	
	public static String readFile(String filename) throws FileNotFoundException, IOException {
		File f = new File(filename);
		FileInputStream fis = new FileInputStream(f);
		byte[] content = new byte[fis.available()];
		fis.read(content);
		String jsContent = new String(content, "UTF-8");
		return jsContent;
	}
	
}
